import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:mall/core/models/ad_config.dart';
import 'package:mall/core/services/auth.dart';
import 'package:mall/screens/main/main_page.dart';
import 'package:mall/screens/splash/components/ad_start_view.dart';

// import 'package:mall_ad/mall_ad.dart';
import 'package:provider/provider.dart';

class SplashPage extends StatefulWidget {
  static const routeName = '/';

  @override
  _SplashPageState createState() => _SplashPageState();
}

class _SplashPageState extends State<SplashPage> {
  AdConfig _adConfig;

  @override
  void initState() {
    super.initState();
    SystemChrome.setEnabledSystemUIOverlays(
      [SystemUiOverlay.bottom],
    );
    _fetchConfig();
  }

  @override
  void dispose() {
    SystemChrome.setEnabledSystemUIOverlays(
      [SystemUiOverlay.top, SystemUiOverlay.bottom],
    );
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          Expanded(
            child: _adConfig == null
                ? Container()
                // : _adConfig.enable
                //     ? MallAdView(
                //         maxSeconds: _adConfig.maxSeconds,
                //         created: (controller) {
                //           controller.fetchAd("splash", "1580");
                //         },
                //         dismiss: () {
                //           Navigator.of(context).pushReplacementNamed(MainPage.routeName);
                //         },
                //       )
                : AdStartView(
                    maxSeconds: _adConfig.maxSeconds,
                    dismiss: () {
                      Navigator.of(context).pushReplacementNamed(MainPage.routeName);
                    },
                  ),
          ),
          // Container(
          //   alignment: Alignment.center,
          //   decoration: BoxDecoration(
          //     color: Colors.white,
          //   ),
          //   height: getProportionateScreenWidth(100),
          //   child: Image.asset(
          //     'assets/images/splash_img_logo.png',
          //     width: getProportionateScreenWidth(200),
          //   ),
          // )
        ],
      ),
    );
  }

  /// 获取广告配置
  void _fetchConfig() async {
    final auth = context.read<Auth>();
    try {
      final result = await auth.adConfig();
      if (!mounted) {
        return;
      }
      final adConfig = result.firstWhere((element) => element.adPositionType == "APP_START_AD");
      setState(() {
        _adConfig = adConfig;
      });
    } on DioError catch (e) {
      if (!mounted) {
        return;
      }
      debugPrint("${e.message}");
      // 如果这个接口失败了，直接导航到主页
      Navigator.of(context).pushReplacementNamed(MainPage.routeName);
    }
  }
}
